<template>  
  <div class="instrument-management">  
    <div class="card">
      <div class="header">
        <h2>乐器管理</h2>  
        <div class="controls">  
          <el-input  
            v-model="searchQuery"  
            placeholder="请输入乐器名称"  
            style="width: 300px;"  
          /> &nbsp; &nbsp; &nbsp; &nbsp; 
          <el-button type="primary" @click="showAddDialog">添加乐器</el-button>  
          <el-button  
            type="danger"  
            @click="batchDelete"  
            :disabled="!selectedInstruments.length"  
          >  
            批量删除  
          </el-button>  
        </div>  
      </div>  

      <el-table  
        :data="filteredInstruments"  
        @selection-change="handleSelectionChange"  
        style="width: 100%"  
        class="instrument-table"  
        stripe highlight-current-row border 
      >  
        <el-table-column type="selection" width="55"></el-table-column>  
        <el-table-column prop="name" label="乐器名" width="150" align="center"></el-table-column>  
        <el-table-column prop="type" label="乐器类型" width="150" align="center"></el-table-column>  
        <el-table-column label="音效" align="center">  
          <template #default="{ row }">
            <audio controls>
              <!-- 拼接音频文件的完整路径 -->
              <source :src="'http://localhost:8080/images/upload/' + row.audio" type="audio/mpeg" />
              您的浏览器不支持音频播放。
            </audio>
          </template>  
        </el-table-column>  
        <el-table-column prop="view_count" label="浏览次数" width="120" align="center"></el-table-column>  
        <el-table-column label="操作" width="200" align="center">  
          <template #default="{ row }">  
            <el-button @click="editInstrument(row)" type="text" size="small">编辑</el-button>  
            <el-button @click="viewInstrument(row)" type="text" size="small">查看</el-button>
            <el-button  
              @click="confirmDelete(row)"  
              type="text"  
              size="small"  
              style="color: red;"  
            >  
              删除  
            </el-button>  
          </template>  
        </el-table-column>  
      </el-table>  

      <!-- 分页 -->
      <el-pagination  
        style="margin-top: 20px;"  
        :current-page="currentPage"  
        :page-size="pageSize"  
        :total="instruments.length"  
        @current-change="handlePageChange"  
        layout="total, prev, pager, next, jumper"  
      />  
    </div>

    <!-- 编辑和添加对话框 -->  
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑乐器' : '添加乐器'" width="700" :before-close="handleClose">  
      <el-form :model="currentInstrument" label-width="80px" ref="instrumentForm">  

        <el-form-item label="乐器名" prop="name" :rules="[{ required: true, message: '请输入乐器名', trigger: 'blur' }]">  
          <el-input v-model="currentInstrument.name"></el-input>  
        </el-form-item>  

        <el-form-item label="乐器类型" prop="type" :rules="[{ required: true, message: '请选择乐器类型', trigger: 'change' }]">  
          <el-select v-model="currentInstrument.type" placeholder="请选择乐器类型">  
            <el-option label="弦鸣乐器" value="弦鸣乐器"></el-option>  
            <el-option label="体鸣乐器" value="体鸣乐器"></el-option>  
            <el-option label="膜鸣乐器" value="膜鸣乐器"></el-option>  
            <el-option label="气鸣乐器" value="气鸣乐器"></el-option>  
            <el-option label="其他" value="其他"></el-option> 
          </el-select>  
        </el-form-item>  

        <el-form-item label="图片" prop="image">  
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/api/instruments/upload"
            :show-file-list="false"
            :on-success="handleSuccess"
          >
            <img v-if="currentInstrument.image" :src="'http://localhost:8080/images/upload/'+currentInstrument.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>  
        
        <el-form-item label="音频" prop="audio">  
          <el-upload
            class="audio-uploader"
            action="http://localhost:8080/api/instruments/upload"
            :show-file-list="false"
            :on-success="handleMusicSuccess"
            :accept="'audio/*'"
          >
            <template #default>
              <!-- 如果已经上传音频，显示音频播放器 -->
              <div v-if="currentInstrument.audio">
                <audio controls style="width: 100%;">
                  <source :src="'http://localhost:8080/images/upload/' + currentInstrument.audio" type="audio/mpeg" />
                  您的浏览器不支持音频播放。
                </audio>
                <a href="#">currentInstrument.audio</a>
              </div>
              <!-- 如果未上传音频，显示上传按钮 -->
              <el-button v-else type="primary" style="display: flex; align-items: center; justify-content: center; padding: 8px 16px;">
                <el-icon-upload style="margin-right: 8px; font-size: 18px;" />
                <span>上传音频</span>
              </el-button>
            </template>
          </el-upload>
        </el-form-item>
   
        <el-form-item label="描述" prop="description" :rules="[{ required: true, message: '请输入描述', trigger: 'blur' }]">  
          <el-input type="textarea" v-model="currentInstrument.description" :rows="6" placeholder="请输入乐器描述"></el-input>  
        </el-form-item>  

        <el-form-item label="文化背景" prop="cultural" :rules="[{ required: true, message: '请输入文化背景', trigger: 'blur' }]">  
          <el-input type="textarea" v-model="currentInstrument.cultural" :rows="6" placeholder="请输入文化背景描述"></el-input>  
        </el-form-item>  

        <el-form-item label="音乐 ID" prop="music_id" :rules="[{ required: true, type: 'number', message: '请输入音乐 ID', trigger: 'blur' }]">  
          <el-input-number v-model="currentInstrument.music_id" :min="1"></el-input-number>  
        </el-form-item>  

      </el-form>  
      <template #footer>  
        <div class="dialog-footer">  
          <el-button @click="dialogVisible = false">取 消</el-button>  
          <el-button type="primary" @click="saveInstrument">确 定</el-button>  
        </div>  
      </template>  
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="查看乐器" width="700" :before-close="handleClose">
      <el-form :model="currentInstrument" label-width="80px" ref="instrumentForm">
        <el-form-item label="乐器名">
          <el-input v-model="currentInstrument.name" disabled></el-input> <!-- 只读 -->
        </el-form-item>

        <el-form-item label="乐器类型">
          <el-select v-model="currentInstrument.type" disabled>
            <el-option label="弦鸣乐器" value="弦鸣乐器"></el-option>
            <el-option label="体鸣乐器" value="体鸣乐器"></el-option>
            <el-option label="膜鸣乐器" value="膜鸣乐器"></el-option>
            <el-option label="气鸣乐器" value="气鸣乐器"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="图片">
          <img v-if="currentInstrument.image" :src="'http://localhost:8080/images/upload/' + currentInstrument.image" class="avatar" />
        </el-form-item>

        <el-form-item label="音频">
          <audio v-if="currentInstrument.audio" controls>
            <source :src="'http://localhost:8080/images/upload/' + currentInstrument.audio" type="audio/mpeg" />
            您的浏览器不支持音频播放。
          </audio>
        </el-form-item>

        <el-form-item label="描述">
          <el-input type="textarea" v-model="currentInstrument.description" :rows="6" disabled></el-input> <!-- 只读 -->
        </el-form-item>

        <el-form-item label="文化背景">
          <el-input type="textarea" v-model="currentInstrument.cultural" :rows="6" disabled></el-input> <!-- 只读 -->
        </el-form-item>

        <el-form-item label="音乐 ID">
          <el-input-number v-model="currentInstrument.music_id" :min="1" disabled></el-input-number> <!-- 只读 -->
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->  
    <el-dialog v-model="confirmDeleteDialogVisible" title="确认删除" width="500" :before-close="handleClose">  
      <span v-if="isBatchDelete">确定要删除所选的乐器吗？此操作不可撤销。</span>
      <span v-else>确定要删除该乐器吗？此操作不可撤销。</span> 
      <template #footer>  
        <div class="dialog-footer">  
          <el-button @click="confirmDeleteDialogVisible = false">取 消</el-button>  
          <el-button type="primary" @click="deleteInstrument">确 定</el-button>  
        </div>  
      </template>  
    </el-dialog>  
  </div>  
</template>  
        

<script>  
import axios from 'axios';  
import { Plus } from '@element-plus/icons-vue'


export default {  
  data() {  
    return {  
      instruments: [], // 乐器列表数据  
      currentInstrument: { instrument_id: '', name: '', type: '', audio: '', view_count: '', image: '', description: '', cultural:'', music_id:''},  
      dialogVisible: false,  
      confirmDeleteDialogVisible: false,  
      selectedInstruments: [],  
      isEdit: false,  
      isBatchDelete: false, 
      currentPage: 1,  
      pageSize: 10,  
      searchQuery: '',  
      detailDialogVisible: false, 
    }
  },  

  computed: {  
    filteredInstruments() {  
      return this.instruments  
        .filter(instrument =>  
          instrument.name.toLowerCase().includes(this.searchQuery.toLowerCase())  
        )  
        .slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);  
    },  
  },  

  methods: { 
    handleSuccess(response){
      this.currentInstrument.image = response;
    },
    handleMusicSuccess(response){      //给上曲成功后的回调函数
      this.currentInstrument.audio = response; 
    },
    fetchInstruments() {  
      axios.get('/api/instruments')  
        .then(response => {  
          console.log("Instruments fetched:", response.data);  
          this.instruments = response.data;  
        })  
        .catch(error => {  
          console.error("Error fetching instruments:", error);  
        });  
    },  
    showAddDialog() {  
      this.dialogVisible = true; 
      this.isEdit = false;  
      this.currentInstrument = { instrument_id: '', name: '', type: '', audio: '', view_count: '', image: '', description: '', cultural:'', music_id:''};   
    },  
    editInstrument(instrument) {  
      this.isEdit = true;  
      this.currentInstrument = { ...instrument }; // 复制当前乐器的属性  
      this.dialogVisible = true; // 显示编辑对话框  
    },  
    viewInstrument(instrument) {
      this.isEdit = false; // 确保不进入编辑模式
      this.currentInstrument = { ...instrument }; // 复制当前乐器的属性
      this.detailDialogVisible = true; // 显示详情对话框
    },
    handleClose(done) {
      this.currentInstrument = { instrument_id: '', name: '', type: '', audio: '', view_count: '', image: '', description: '', cultural:'', music_id:'' };
      done();
    },
    confirmDelete(instrument) {  
      this.isBatchDelete = false;
      this.currentInstrument = instrument;  
      this.confirmDeleteDialogVisible = true;  
    },  
    batchDelete() {
      if (!this.selectedInstruments.length) return;
      this.isBatchDelete = true; // 标记为批量删除
      this.confirmDeleteDialogVisible = true; // 打开确认删除对话框
    },
    deleteInstrument() {
      if (this.isBatchDelete) {
        // 批量删除逻辑
        const idsToDelete = this.selectedInstruments.map(instrument => instrument.instrument_id);
        const deleteRequests = idsToDelete.map(id =>
          axios.delete(`/api/instruments/${id}`)
        );

        Promise.all(deleteRequests)
          .then(() => {
            this.instruments = this.instruments.filter(instrument => !idsToDelete.includes(instrument.instrument_id));
            this.selectedInstruments = []; // 清空已选择的乐器
            this.$message({
              type: 'success',
              message: '批量删除成功！',
            });
          })
          .catch(error => {
            console.error("Error deleting instruments:", error);
            this.$message({
              type: 'error',
              message: '部分删除操作失败，请稍后重试！',
            });
          });
      } else {
        // 单项删除逻辑
        axios.delete(`/api/instruments/${this.currentInstrument.instrument_id}`)
          .then(() => {
            this.instruments = this.instruments.filter(instrument => instrument.instrument_id !== this.currentInstrument.instrument_id);
            this.$message({
              type: 'success',
              message: '删除成功！',
            });
          })
          .catch(error => {
            console.error("Error deleting instrument:", error);
          });
      }
      this.confirmDeleteDialogVisible = false; // 关闭删除对话框
    },
    saveInstrument() {  
      if (this.isEdit) {  
        // 更新乐器信息  
        axios.put(`/api/instruments/${this.currentInstrument.instrument_id}`, this.currentInstrument)  
          .then(() => {  
            const index = this.instruments.findIndex(inst => inst.instrument_id === this.currentInstrument.instrument_id);  
            if (index !== -1) {  
              // 直接通过索引更新乐器信息  
              this.instruments[index] = { ...this.currentInstrument };  
            }  
            this.dialogVisible = false; // 关闭对话框 
            this.$message({
              type: 'success',
              message: '更新成功！',
            });  
          })  
          .catch(error => {  
            console.error("Error updating instrument:", error);  
          });  
      } else {  
        // 添加新乐器  
        axios.post('/api/instruments', this.currentInstrument)  
          .then(response => {  
            this.instruments.push(response.data);  
            this.$message({
              type: 'success',
              message: '添加成功！',
            }); 
          })  
          .catch(error => {  
            console.error("Error adding instrument:", error);  
          });  
          this.dialogVisible = false; // 关闭对话框  
      }   
    }, 
    handleSelectionChange(selected) {  
      this.selectedInstruments = selected;  
    },  
    handlePageChange(page) {  
      this.currentPage = page;  
    },  
  },  
  
  components:{
    Plus
  },
  
  mounted() {  
    this.fetchInstruments(); // 组件挂载时调用获取乐器数据  
  },  
};  
</script>  


<style scoped>  
.instrument-management {  
  padding: 20px;  
  background-color: #f5f5f5;  
  border-radius: 8px;  
}  

.card {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.header {  
  display: flex;  
  justify-content: space-between;  
  align-items: center;  
  margin-bottom: 20px;  
}  

.controls {  
  display: flex;  
  align-items: center;  
}  

.controls el-input {  
  margin-right: 20px;  
}  

.instrument-table {  
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);  
  border-radius: 8px;  
  overflow: hidden;  
  background-color: #ffffff;  
}  

.dialog-footer {  
  display: flex;  
  justify-content: flex-end;  
}  
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>